﻿using System;
using System.IO;
using System.Text;

namespace Bouyei.Discoverer.Class
{
    public class FileStorage
    {
        public FileStorage()
        { }

        public bool Write(string path,string content)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    byte[] buf = Encoding.UTF8.GetBytes(content);
                    fs.Write(buf, 0, buf.Length);

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool Write(string path,byte[] buf)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public bool Write(string path,StringBuilder sb)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    byte[] buf = Encoding.UTF8.GetBytes(sb.ToString());
                    fs.Write(buf, 0, buf.Length);

                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        public byte[] Read(string path)
        {
            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    byte[] buf = new byte[fs.Length];
                    int count = fs.Read(buf, 0, buf.Length);
                  
                    while (count < buf.Length)
                    {
                        int c = fs.Read(buf, count, buf.Length - count);
                        if (c <= 0) break;
                        count += c;
                    }
                    return buf;
                }
            }
            catch
            {
                return null;
            }
        }

    }
}
